package utils

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
)

func PostJson(url string, json string) (string, error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(json)))
	req.Header.Set("Content-Type", "application/json")
	// req.Header.Set("Authorization", "Basic YWRtaW46a29ueXVuQDIwMjI=")
	if err != nil {
		fmt.Println("请求三方接口出错")
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	return string(body), err
}

func PostForm(url string) (string, error) {
	resp, err := http.PostForm(url, nil)
	resp.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		// panic(err)
		fmt.Println(err)
	}
	defer resp.Body.Close()
	return string(body), err
}

func Get(url string) (string, error) {
	resp, err := http.Get(url)
	resp.Header.Add("Content-Type", "application/json")
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	return string(body), err
}
